/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import * as fse from 'fs-extra';

import { OhosLogger } from './log/ohos-logger.js';

const logger: OhosLogger = OhosLogger.getLogger('SourceMap');

/**
 * 在 ohos-test-coverage 场景用测试框架覆盖率生成的 sourceMap 替换 sdk 生成的 sourceMaps.map 文件内容。
 * 因为覆盖率场景 rollup 生成的 sourceMap是不对的，测试框架覆盖率自己生成的 sourceMap 是对的。
 *
 * @param defaultSourceMapPath 原始的sourceMap全路径
 * @param coverageSourceMapPath 测试框架覆盖率生成的sourceMap全路径
 */
export async function overWriteSourceMap(defaultSourceMapPath: string, coverageSourceMapPath: string) {
  if (!fse.existsSync(defaultSourceMapPath) || !fse.existsSync(coverageSourceMapPath)) {
    return;
  }
  try {
    let coverageSourceMapString = fse.readFileSync(coverageSourceMapPath).toString();
    if (coverageSourceMapString.endsWith(',')) {
      coverageSourceMapString = coverageSourceMapString.substring(0, coverageSourceMapString.length - 1);
    }
    coverageSourceMapString = '{' + coverageSourceMapString + '}';
    const coverageSourceMapMapJson = JSON.parse(coverageSourceMapString);
    const defaultSourceMapJson = await fse.readJSON(defaultSourceMapPath);

    // 遍历覆盖率sourceMap,根据key再去defaultSourceMap里面和sources匹配，如果匹配到就覆盖defaultSourceMap的mappings
    Object.keys(coverageSourceMapMapJson).forEach(key => {
      const mappings = coverageSourceMapMapJson[key]['mappings'];
      if (!mappings) {
        return;
      }
      for (let value of Object.values(defaultSourceMapJson)) {
        const originSourceMap = value as any;
        if (originSourceMap.sources && originSourceMap.sources.length === 1 && originSourceMap.sources[0] === key) {
          originSourceMap['mappings'] = mappings;
          break;
        }
      }
    });

    // 覆盖后写入文件
    await fse.writeJSON(defaultSourceMapPath, defaultSourceMapJson, {spaces: 2, encoding: 'utf8'});
  } catch (e: any) {
    logger.debug(`overWriteSourceMap error ${e?.message}`);
  }
}